//
//  GoogleMapViewController.m
//  iPhoneKML
//
//  Created by Benjamin Blundell on 17/11/2009.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "GoogleMapViewController.h"


@implementation GoogleMapViewController

@synthesize locationManager;
@synthesize bestEffortAtLocation;




- (void) setLatitude:(float) lat andLongitude:(float) lon andTitle:(NSString*) t {

	location = gmapView.userLocation.coordinate;
	
	self.navigationItem.title = t;
	
	MKCoordinateRegion region;
	MKCoordinateSpan span;
	span.latitudeDelta=0.02;
	span.longitudeDelta=0.02;
	
	
	
	location.latitude= lat;
	location.longitude= lon;
	region.span=span;
	region.center=location;
	
	
	[gmapView setRegion:region animated:TRUE];
	[gmapView regionThatFits:region];

	CLLocationCoordinate2D loc;
	loc.latitude = lat;
	loc.longitude = lon;
	
	if (mPlacemark){
		[gmapView removeAnnotation:mPlacemark];
		[mPlacemark release];
	}
	
	mPlacemark = [[MKPlacemark alloc ]initWithCoordinate: loc addressDictionary: nil];
	[gmapView addAnnotation:mPlacemark];

	
}

/*+ (CLLocation *) wakkawakka: (CLLocation*) loc {
#ifdef TARGET_IPHONE_SIMULATOR
		return [[CLLocation alloc] initWithLatitude:10.0 longitude:20.0];
#else
	
		return loc;
#endif
}*/


- (IBAction)start:(id)sender {
	
	if (self.locationManager == nil){
		self.locationManager = [[[CLLocationManager alloc] init] autorelease];
		self.locationManager.delegate = self;
		self.locationManager.desiredAccuracy = [[NSNumber numberWithDouble:kCLLocationAccuracyBest] doubleValue];
		[self.locationManager startUpdatingLocation];
		[self performSelector:@selector(stopUpdatingLocation:) withObject:@"Timed Out" afterDelay: [[NSNumber numberWithDouble:30] doubleValue]];
	}
	
	
}

	


 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
		
    }
    return self;
}*/


/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

}



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
		
	gmapView.showsUserLocation=TRUE;
	
		
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
	[self.locationManager release];
    [self.bestEffortAtLocation release];
	
}

#pragma mark -
#pragma mark CoreLocation delegate Methods

/*
 * We want to get and store a location measurement that meets the desired accuracy. For this example, we are
 *      going to use horizontal accuracy as the deciding factor. In other cases, you may wish to use vertical
 *      accuracy, or both together.
 */
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

	
    // test the age of the location measurement to determine if the measurement is cached
    // in most cases you will not want to rely on cached measurements
    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
    if (locationAge > 5.0) return;
    // test that the horizontal accuracy does not indicate an invalid measurement
    if (newLocation.horizontalAccuracy < 0) return;
	
	
	CLLocationCoordinate2D coord = newLocation.coordinate;
	NSString *end = [[NSString alloc] initWithFormat: @"%f,%f", coord.latitude,coord.longitude];
	NSString *start = [[NSString alloc] initWithFormat: @"%f,%f", location.latitude,location.longitude];
	
	
	// Not sure if we can do routing inside our app so we need to simply launch the "Maps" app
	
	NSString *urlstring = [[NSString alloc] initWithFormat: @"http://maps.google.com/maps?saddr=%@&daddr=%@",start,end]; 
	
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString: urlstring]];
/*	[start release];
	[end release];
	[urlstring release];*/
	
	
  
 /*   if (bestEffortAtLocation == nil || bestEffortAtLocation.horizontalAccuracy > newLocation.horizontalAccuracy) {
     
        self.bestEffortAtLocation = newLocation;
               if (newLocation.horizontalAccuracy <= locationManager.desiredAccuracy) {
                     [self stopUpdatingLocation:NSLocalizedString(@"Acquired Location", @"Acquired Location")];
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(stopUpdatingLocation:) object:nil];
        }
    }*/
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    // The location "unknown" error simply means the manager is currently unable to get the location.
    // We can ignore this error for the scenario of getting a single location fix, because we already have a 
    // timeout that will stop the location manager to save power.
    if ([error code] != kCLErrorLocationUnknown) {
        [self stopUpdatingLocation:NSLocalizedString(@"Error", @"Error")];
    }
}

- (void)stopUpdatingLocation:(NSString *)state {
    [self.locationManager stopUpdatingLocation];
    self.locationManager.delegate = nil;
}




@end
